//
//  ViewController.m
//  天气预报
//
//  Created by wangda on 15/7/10.
//  Copyright (c) 2015年 wang. All rights reserved.
//

#import "ViewController.h"
#import "LBBlurredImage/UIImageView+LBBlurredImage.h"
#import "Masonry.h"
#import "OpenWeatherMapInterface.h"
#import "TableViewCell.h"
#import "CBChartView.h"
#import "ThreeHoursData.h"

#define _height self.view.frame.size.height
#define _width self.view.frame.size.width



@interface ViewController ()
@property (strong,nonatomic)UIImageView *blurredView;
@property (strong,nonatomic)UITableView *tableView;
@property (strong,nonatomic)UIScrollView *scrollView;
@property (strong,nonatomic)CurrentWeatherData * weatherCurrentData;
@property (strong,nonatomic)NSMutableArray *hoursTempreture;
@property (strong,nonatomic)NSMutableArray *daysTempreture;
@property (strong,nonatomic)NSString *intString;

//背景图片的轮流播放
@property(nonatomic,strong) NSTimer *timer;
@property(nonatomic,strong) UIImageView *backGround;



//滑动手势和分页控制
@property(nonatomic,strong) UISwipeGestureRecognizer *recognizerRight;
@property(nonatomic,strong) UISwipeGestureRecognizer *recognizerLeft;
@property(nonatomic,strong) UIPageControl *pg;


//首页的布局控件
@property(nonatomic,strong) UILabel *cityname;
@property(nonatomic,strong) UIImageView *weatherImage;
@property(nonatomic,strong)  UILabel *weatherLabel;
@property(nonatomic,strong) UILabel *currentTempretureLabel;
@property(nonatomic,strong) UILabel *tempretureRangeLabel;



@end

static NSString *Cell = @"TableViewCell";


@implementation ViewController


-(void)getWeatherDataByCityname:(NSString *)cityname
{
    
    self.weatherCurrentData=[OpenWeatherMapInterface getCurrentDataWithCityName:cityname  andCountryCode:nil];
    self.hoursTempreture=[OpenWeatherMapInterface getOneDayWwatherDataWithCityName:cityname andCountryCode:nil];
    self.daysTempreture = [OpenWeatherMapInterface getFifteenDayWwatherDataWithCityName:cityname andCountryCode:nil];
}


-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recongnizer
{
     int page = self.pg.currentPage ;
    if (recongnizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        NSLog(@"left");
       
        page--;
        if (page<0) return;
        else
            self.pg.currentPage = page;
        
    }
    if (recongnizer.direction == UISwipeGestureRecognizerDirectionRight) {
        NSLog(@"right");
        page++;
        if (page >4) return;
        else
            self.pg.currentPage = page;
        
    }
    
    switch (self.pg.currentPage) {
        case 0:
            [self getWeatherDataByCityname:@"南京"];
            break;
        case 1:
            [self getWeatherDataByCityname:@"北京"];
            break;
        case 2:
            [self getWeatherDataByCityname:@"上海"];
            break;
        case 3:
            [self getWeatherDataByCityname:@"广州"];
            break;
        case 4:
            [self getWeatherDataByCityname:@"深圳"];
            break;
        default:
            break;
    }
    
    [self setTheCurrentMessage:self.weatherCurrentData];
    [self.tableView reloadData];

}

-(void)loadView
{
    //[super loadView];
    NSLog(@"ddddd");
    self.view = [[UIView alloc]init];
    //self.view.backgroundColor = [UIColor redColor];
   // [self viewDidLoad];
}


- (void)viewDidLoad {
   [super viewDidLoad];
    
    NSLog(@"aaaaaaaaa");
    self.recognizerRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    self.recognizerLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    
    [self.recognizerLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.view addGestureRecognizer:self.recognizerLeft];
    
    [self.recognizerRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:self.recognizerRight];
    //self.cityName = @"南京";
    self.weatherCurrentData =[[CurrentWeatherData alloc]init];
    
    [self getWeatherDataByCityname:@"南京"];
    [self setAllLayOut];
    
    UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:Cell];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
}





#pragma mark - AllLayout 
    //设置整体布局
-(void)setAllLayOut
{
        //整体布局
    UIImage * backgroundImage = [UIImage imageNamed:@"bg3"];
        // Do any additional setup after loading the view, typically from a nib.
    self.backGround =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _width,_height )];
    
    
    
    self.backGround.image = backgroundImage;
    
    
    
    
    [self.view addSubview:self.backGround];
    
    
    self.backGround.contentMode=UIViewContentModeScaleAspectFill;
        //模糊视图
    self.blurredView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _width,_height )];
    [self.blurredView setImageToBlur:backgroundImage blurRadius:10 completionBlock:nil];
    self.blurredView.alpha =0;
    [self.backGround addSubview:self.blurredView];
    
        //滚动图
    self.scrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, _width,_height)];
    self.scrollView.backgroundColor=[UIColor clearColor];
    self.scrollView.contentSize=CGSizeMake(_width, _height*3);
    self.scrollView.scrollEnabled=YES;
    self.scrollView.pagingEnabled=YES;
    self.scrollView.delegate=self;
    [self.view addSubview:self.scrollView];
    
        // 使用
    CBChartView *chartView = [[CBChartView alloc]init];
    chartView.shutDefaultAnimation = YES;
    [self.scrollView addSubview:chartView];
    NSRange rangeTime =NSMakeRange(11, 2);
    NSMutableArray *xValueArr=[[NSMutableArray alloc]init];
    NSMutableArray *yValueArr=[[NSMutableArray alloc]init];
    float maxTem =-100;
    float minTem =100;
    for (ThreeHoursData * temp in self.hoursTempreture) {
        [xValueArr addObject:[temp.date  substringWithRange:rangeTime]];
        [yValueArr addObject:[temp.temperature stringValue]];
        if (maxTem<[temp.temperature floatValue]) {
            maxTem=[temp.temperature floatValue];
        }
        if (minTem>[temp.temperature floatValue]) {
            minTem=[temp.temperature floatValue];
        }
    }
    
    chartView.xValues = xValueArr;
    chartView.yValues = yValueArr;
    chartView.chartWidth = 2.0;
    chartView.chartColor = [UIColor whiteColor];
    
    [UIView animateWithDuration:1 animations:^{
        chartView.frame = CGRectMake(10, 110, 310, 300);
    }];
    
    CGRect viewBounds = self.view.frame;
    viewBounds.origin.y = 0;
    viewBounds.size.height = 460;
    
    
    self.pg = [[UIPageControl alloc]initWithFrame:CGRectMake(viewBounds.origin.x, viewBounds.origin.y, viewBounds.size.width,
                                                             60)];
    self.pg.backgroundColor = [UIColor grayColor];
    self.pg.alpha = 0.1;
    self.pg.numberOfPages = 5;
    self.pg.currentPage = 0;
      [self.view addSubview:self.pg];
    
     //之前不明白 scrollview控制大小的地方在哪边，现在明白了。
        //滚动图里的表格
    self.tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, _height, _width,_height*2)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorColor = [UIColor colorWithWhite:1 alpha:0.0];
    self.tableView.pagingEnabled = YES;
    [self.scrollView  addSubview:self.tableView];
    self.weatherCurrentData.tempLow=[NSNumber numberWithFloat:minTem];
    self.weatherCurrentData.tempHigh=[NSNumber numberWithFloat:maxTem];
    //城市名称
    self.cityname = [[UILabel alloc]init];
    self.cityname.font = [UIFont fontWithName:nil size:20];
    self.cityname.textColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.cityname];
    [self.cityname mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.scrollView.mas_centerX);
        make.top.equalTo(self.scrollView.mas_top).with.offset(35);
    }];
    
    self.weatherImage  =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"weather-moon"]];
    [self.scrollView addSubview:self.weatherImage];
    [self.weatherImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView.mas_left).with.offset(70);
        make.bottom.equalTo(self.tableView.mas_top).with.offset(-269);
        make.height.equalTo(@30);
        make.width.equalTo(@30);
    }];
    
    //晴，多云等
    self.weatherLabel =[[UILabel alloc]init];
        [self.scrollView addSubview:self.weatherLabel];
    self.weatherLabel.font=[UIFont fontWithName:nil size:15];
    self.weatherLabel.textColor=[UIColor whiteColor];

    [self.weatherLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.weatherImage.mas_centerY);
        make.left.equalTo(self.weatherImage.mas_right).with.offset(8);
    }];
    self.currentTempretureLabel =[[UILabel alloc]init];
    self.currentTempretureLabel.font=[UIFont fontWithName:@"HelveticaNeue-UltraLight" size:100];
    self.currentTempretureLabel.textColor=[UIColor whiteColor];

    [self.scrollView addSubview:self.currentTempretureLabel];
    [self.currentTempretureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.scrollView.mas_centerX);
        make.top.equalTo(self.scrollView.mas_top).with.offset(60);
    }];

    
    self.tempretureRangeLabel =[[UILabel alloc]init];
    self.tempretureRangeLabel.font=[UIFont fontWithName:@"HelveticaNeue-UltraLight" size:20];
    self.tempretureRangeLabel.textColor=[UIColor whiteColor];

       [self.scrollView addSubview:self.tempretureRangeLabel];
    [self.tempretureRangeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.currentTempretureLabel.mas_bottom).with.offset(10);
        make.right.equalTo(self.currentTempretureLabel.mas_right);
     
    }];
    
    
    NSLog(@"buju  ok  --------------------");
    [self setTheCurrentMessage:self.weatherCurrentData];
    
}


 
#pragma  mark - setImmediatelyInformation
-(void)setTheCurrentMessage:(CurrentWeatherData *)data
{
    
    self.cityname.text = data.locationName;
    self.weatherLabel.text=data.conditionDescription;
    self.currentTempretureLabel.text=[NSString stringWithFormat:@"%.fº",[data.temperature floatValue]];
    self.tempretureRangeLabel.text=[NSString stringWithFormat:@"%.fº-%.fº",[data.tempLow floatValue],[data.tempHigh floatValue]];
   
 
    UIImageView *weatherImage1 =[[UIImageView alloc]initWithImage:[UIImage imageNamed:data.icon]];
    self.weatherImage =  weatherImage1;
   
    
    
  
    
   // [self addTimer];  暂时先不开启。。。晃眼
}

#pragma  mark - tableView delegate 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.hoursTempreture.count+1;
    }else{
        return self.daysTempreture.count+1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
    if (! cell) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:Cell];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.conditionLabel.textColor = [UIColor whiteColor];
    cell.TimeLabel.textColor = [UIColor whiteColor];
    cell.tempLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.1];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.detailTextLabel.textColor = [UIColor whiteColor];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.conditionLabel.text = nil;
            cell.TimeLabel.text = nil;
            cell.tempLabel.text = nil;
            NSString *dateStr = [OpenWeatherMapInterface getDay];
            [self configureHeaderCell:cell title:dateStr];
        }
        else {
            cell.imageView.image =[UIImage imageNamed:[self.hoursTempreture[indexPath.row-1] valueForKey:@"icon"]];
            cell.TimeLabel.text = [NSString stringWithFormat:@"%@ %@",  [[[self.hoursTempreture[indexPath.row-1] valueForKey:@"date"] substringFromIndex:11] substringToIndex:2],[self.hoursTempreture[indexPath.row-1] valueForKey:@"hour"]];
            NSLog(@"----------------------text is %@",cell.TimeLabel.text);
            cell.tempLabel.text =[NSString stringWithFormat:@"%d℃",[[self.hoursTempreture[indexPath.row-1] valueForKey:@"temperature"] intValue]];
            cell.conditionLabel.text = [self.hoursTempreture[indexPath.row-1] valueForKey:@"condition"];
        }
    }
    else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.conditionLabel.text = nil;
            cell.TimeLabel.text = nil;
            cell.tempLabel.text = nil;
           [self configureHeaderCell:cell title:@"一周天气"];
        }
        else {
            
            int tempHigh = [[self.daysTempreture[indexPath.row-1] tempHigh] intValue];
            int tempLow = [[self.daysTempreture[indexPath.row-1] tempLow] intValue];
            NSString *icon1 = [self.daysTempreture[indexPath.row-1] icon];
            cell.imageView.image =[UIImage imageNamed:icon1];
            cell.tempLabel.text = [NSString stringWithFormat:@"%d/%d℃",tempHigh,tempLow];
            cell.TimeLabel.text = [self.daysTempreture[indexPath.row-1] valueForKey:@"weekDay"];
            cell.conditionLabel.text = [self.daysTempreture[indexPath.row-1] valueForKey:@"condition"];
        }
    }
    return cell;
    
    
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger cellCount = [self tableView:tableView numberOfRowsInSection:indexPath.section];
    return _height / ((CGFloat)cellCount);
}




- (void)configureHeaderCell:(UITableViewCell *)cell title:(NSString *)title {
    cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
    cell.textLabel.text = title;
    cell.detailTextLabel.text = @"";
    cell.imageView.image = nil;
}



#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat height = scrollView.bounds.size.height;
    CGFloat position = MAX(scrollView.contentOffset.y, 0.0);
    CGFloat percent = MIN(position / height, 1.0);
    self.blurredView.alpha = percent;
}




-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"ade0c46e82a50e4d21ba134779d94254" forHTTPHeaderField: @"apikey"];

    NSURLResponse *res = [[NSURLResponse alloc]init];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:nil];
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    self.cityName =[dict[@"retData"] objectForKey:@"city"];

}
static int i = 0;
-(void)nextImage
{
    NSLog(@"in timer~~~~");
    
    UIImage *backgroundImage;
    if(i == 0)
    {
       backgroundImage  = [UIImage imageNamed:@"bg1"];
        NSLog(@"in i =0 ");
    }
    if (i==1) {
        backgroundImage = [UIImage imageNamed:@"bg2"];
        NSLog(@"in i =1 ");

    }
    if (i==2) {
       backgroundImage = [UIImage imageNamed:@"bg3"];
        i=-1;
        NSLog(@"in i =2 ");

    }
    i++;
    
    
    //--------------虽然实现了，但是对于一些参数的改变还是显得没有生效，没有那么顺手好用啊
    CATransition *animation = [CATransition animation];
    [animation setDuration:1.25f];
    //[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    //[animation setType:kCATransitionReveal];
    //[animation setType:kCAEmitterBehaviorDrag];
    [animation setType:kCAEmitterBehaviorColorOverLife];
    
    [animation setSubtype: kCATransitionFromBottom];
    self.backGround.image = backgroundImage;
    [self.view.layer addAnimation:animation forKey:@"Reveal"];
    // [self.view.layer addAnimation:animation forKey:@"cube"];
       // Do any additional setup after loading the view, typically from a nib.
   // UIImageView *backGround =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _width,_height )];
    /*[UIView animateWithDuration:1.2 animations:^{
        
     
       // self.backGround.alpha = 0.5;
        
      //  self.backGround.alpha = 1.0;
    }];*/
   
    [self.blurredView setImageToBlur:backgroundImage blurRadius:10 completionBlock:nil];
   /* int page = (int)self.pageControl.currentPage;
        if (page == 2) {
               page = 0;
          }else
              {
                      page++;
                   }
  
    //  滚动scrollview
      CGFloat x = page * self.scrollView.frame.size.width;
       self.scrollView.contentOffset = CGPointMake(x, 0);*/
}
//开启定时器
-(void)addTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
}

//关闭定时器
-(void)removeTimer{
    [self.timer invalidate];
}

@end
